<?php defined('IN_LK') or die('Access Denied');
lk::lo_app('admin_common', 'admin', 0);
class index extends admin_common
{
	/**
	 * admin_model 句柄
	 */
	private $db;
	
	/**
	 * times_model 句柄
	 */
	private $times_db;
	
	/**
	 * admin_panel_model 句柄
	 */
	private $panel_db;
	
	/**
	 * menu_model 句柄
	 */
	private $menu_db;
	
	public function __construct()
	{
		parent::__construct();
		$this->db = lk::load_model('admin');
		$this->menu_db  = lk::load_model('menu');
		$this->panel_db = lk::load_model('admin_panel');
	}
	
	public function initialize()
	{
		if(isset($_SESSION['roleid']))
		{
			if(!($menus = get_cache('menu_role' . $_SESSION['roleid'])))
			{
				$menus = parent::supmenu();
			}
			$guides   = json_encode($menus['guides']);
			$title    = json_encode($menus['title']);
			$my_menu  = json_encode($this->get_panel());
			$username = get_cookie('username');
			$role_arr = get_cache('admin_role');
			$role     = $role_arr[$_SESSION['roleid']];
			include self::admin_t('index');
		}
	}
		
	/**
	 * 退出
	 */
	public function logout($no = 0)
	{
		parent::login_set();
		if($no)
		{
			return;
		}
		showmsg(LANG('logout_success'), true, '?m=admin&c=index&a=login');
	}
	
	/**
	 * 登录
	 */
	public function login()
	{
		if(isset($_POST['dosubmit']))
		{
			$captcha = isset($_POST['captcha']) && $_POST['captcha'] ? trim($_POST['captcha']) : showmsg(LANG('captcha_not_null'));
			if($_SESSION['captcha'] !== strtolower($captcha))
			{
				showmsg(LANG('captcha_is_wrong'));
			}
			$username = isset($_POST['username']) && $_POST['username'] ? trim($_POST['username']) : showmsg(LANG('username_not_null'));
			$password = isset($_POST['password']) && $_POST['password'] ? trim($_POST['password']) : showmsg(LANG('password_not_null'));
			
			/**
			 * 检查登录次数
			 */
			$this->times_db = lk::load_model('times');
			$this->times_db->time_set($username);
			$res = $this->times_db->time_get();
			if($this->times_db->denied())
			{
				$have = LOCKTIME/60 - floor((TIME - $res['time'])/60);
				showmsg(sprintf(LANG('please_wait_hour'), $have), false, '', false);
			}
			$user = $this->db->get_one('', "`username`='$username'");
			if(!$user)
			{
				showmsg(LANG('user_not_exist'));
			}
			if($user['password'] != password($password))
			{
				$dt = (int)$res['times'] == MAXLOGINTIMES ? 0 : (int)$res['times'];
				$leave = max(MAXLOGINTIMES - $dt, 0);
				$this->times_db->add();
				showmsg(sprintf(LANG('password_not_right'), $leave));
			}
			else
			{
				$this->times_db->clear();
			}
			
			/**
			 * 记住用户名
			 */
			if(isset($_POST['jizhu']) && $_POST['jizhu'])
			{
				set_cookie('username', $username, TIME + 86400*30);
			}
			else
			{
				set_cookie('username');
			}
			$this->db->update(array('lastloginip'=>get_ip(), 'lastlogintime'=>TIME, 'logintimes'=>'+=1'), '`userid`=\'' . $user['userid'] . '\'');
			parent::login_set($user);
			showmsg(LANG('login_success'), true, 'index.php?m=admin&c=index');
		}
		else
		{
			include self::admin_t('login');
		}
	}
	
	/**
	 * 后台首页
	 */
	public function main()
	{
		lk::lf_app('admin');
		$userid        = $_SESSION['userid'];
		$username      = get_cookie('username');
		$role_arr      = get_cache('admin_role');
		$role          = $role_arr[$_SESSION['roleid']];
		$userinfo      = $this->db->get_one('', "`userid`='$userid'");
		$lastlogintime = date('Y-m-d H:i:s', $userinfo['lastlogintime']);
		$lastloginip   = $userinfo['lastloginip'];
		$logintimes    = $userinfo['logintimes'];
		$my_menu       = json_encode($this->get_panel());
		$system_info = self::system_info();
		include self::admin_t('main');
	}
	
	/**
	 * 添加快捷菜单
	 */
	public function add_panel()
	{
		$id = isset($_POST['menuid']) && $_POST['menuid'] ? (int)$_POST['menuid'] : 0;
		if(!$id)
		{
			return false;
		}
		$res = $this->menu_db->get_one('name,title,m,c,a', "`id`='$id'");
		if(!$res)
		{
			return false;
		}
		if($this->panel_db->get_one('menuid', "`menuid`='$id' AND `userid`='" . $_SESSION['userid'] . "'"))
		{
			return false;
		}
		$url  = '?m=' . $res['m'] . '&c=' . $res['c'] . '&a=' . $res['a'];
		$data = array('menuid'      => $id,
		              'userid'  => $_SESSION['userid'],
					  'title'   => $res['title'],
					  'url'     => $url,
					  'datetime'=> TIME);
		if($this->panel_db->insert($data))
		{
			echo json_encode(array('url' => $url, 'title' => $res['title']));
		}
	}
	
	/**
	 * 读取快捷菜单
	 */
	private function get_panel()
	{
		if(!isset($_SESSION['userid']))
		{
			return false;
		}
		$menu = $this->panel_db->get('menuid', "`userid`='" . $_SESSION['userid'] . "'");
		if($menu)
		{
			foreach($menu as $menuid)
			{
				$ids[] = $menuid['menuid'];
			}
		}
		else
		{
			return false;
		}
		$ids = implode('\',\'', $ids);
		$menu = $this->menu_db->get('name,parentid,title,id', "`id` IN ('$ids')");
		foreach($menu as $m_key => $m_value)
		{
			$p = $this->menu_db->get_one('name', "`id`='" . $m_value['parentid'] . "'");
			$menu[$m_key]['parent'] = $p['name'];
			unset($menu[$m_key]['parentid']);
		}
		return $menu;
	}
	
	/**
	 * 删除快捷菜单
	 */
	public function delete_panel()
	{
		$menuid = isset($_GET['id']) ? (int)$_GET['id'] : 0;
		if(!$menuid)
		{
			return false;
		}
		if($this->panel_db->delete("`menuid`='$menuid' AND `userid`='" . $_SESSION['userid'] . "'"))
		{
			echo true;
		}
	}
	
	/**
	 * 获取版本及服务器信息
	 */
	static private function system_info()
	{
		$data = array();
		@$GD = gd_info();
		$data['php_version']          = PHP_OS . PHP_VERSION;
		$data['server_software']      = $_SERVER['SERVER_SOFTWARE'];
		$data['server_port']          = $_SERVER['SERVER_PORT'];
		$data['http_accept_language'] = getenv("HTTP_ACCEPT_LANGUAGE");
		$data['mysql_version']    = mysql_get_server_info();
		$data['disk_free_space']  = function_exists('disk_free_space') ? bytes2human(disk_free_space('.')) : '未知';
		$data['gd']               = function_exists('imagecreate') ? $GD['GD Version'] : '不支持GD库';
		$data['safe_mode']        = ini_get('safe_mode') ? '是' : '否';
		$data['register_globals'] = ini_get('register_globals') ? '打开' : '关闭';
		$data['magic_quotes_gpc'] = get_magic_quotes_gpc() ? '打开' : '关闭';
		$data['post_max_size']    = ini_get('post_max_size');
		$data['upload_max_filesize'] = ini_get('upload_max_filesize');
		$data['allow_url_fopen']  = ini_get('allow_url_fopen') ? '支持' : '不支持';
		$data['execution_time']   = ini_get('max_execution_time');
		return $data;
	}

	/**
	 * 自助修改密码
	 */
	public function edit_pwd()
	{
		if(isset($_POST['oldpwd']) && isset($_POST['newpwd']) && isset($_POST['newpwd2']) && $_POST['newpwd'] == $_POST['newpwd2'] && !empty($_POST['oldpwd']) && !empty($_POST['newpwd']) && !empty($_POST['newpwd2']))
		{
			$admin_op = lk::lo_app('admin_manage', 'admin', 1);
			if(!$admin_op->is_right_oldpwd($_SESSION['userid'], $_POST['oldpwd']))
			{
				showmsg(LANG('old_password_is_wrong'), false, HTTP_REFERER);
			}
			if($admin_op->edit_pwd($_SESSION['userid'], $_POST['newpwd2']))
			{
				$this->logout(1);
				showmsg(LANG('update_success'), true, '?m=admin&c=index&a=login', true, '', true);
			}
		}
		$admin_info = $this->db->get_one('username,email', '`userid`=\'' . $_SESSION['userid'] . '\'');
		$username = $admin_info['username'];
		$email    = $admin_info['email'];
		include self::admin_t('admin_edit_pwd');
	}
	
	/**
	 * 检查密码是否正确
	 */
	public function check_pwd_ajax()
	{
		$res = false;
		if(isset($_GET['oldpwd']) && $_GET['oldpwd'])
		{
			$admin_op = lk::lo_app('admin_op', 'admin', 1);
			$res = $admin_op->is_right_oldpwd($_SESSION['userid'], $_GET['oldpwd']);
		}
		$res = (boolean)$res;
		$res ? exit('1') : exit('0');
	}
	
	/**
	 * 自助编辑信息
	 */
	public function edit_user()
	{
		if(isset($_POST['dosubmit']) && isset($_POST['email']) && $_POST['email'])
		{
			if(!is_email($_POST['email']))
			{
				showmsg(LANG('email_illegal'), false);
			}
			if($this->db->update(array('email'=>$_POST['email']), '`userid`=\'' . $_SESSION['userid'] . '\''))
			{
				showmsg(LANG('update_success'), true, HTTP_REFERER);
			}
		}
		$admin_info = $this->db->get_one('username,lastlogintime,lastloginip,email', '`userid`=\'' . $_SESSION['userid'] . '\'');
		$admin_info = array_values($admin_info);
		list($username, $lastlogintime, $lastloginip, $email) = $admin_info;
		$lastlogintime = date('Y-m-d H:i:s', $lastlogintime);
		include self::admin_t('admin_edit_user');
	}
	
	/**
	 * 检查其输入的Email是否存在
	 */
	public function check_email_ajax()
	{
		$res = false;
		if(isset($_GET['email']) && $_GET['email'])
		{
			$email = $_GET['email'];
			$res = $this->db->get_one('userid', "`email`='$email' AND `userid`!='" . $_SESSION['userid'] . "'");
		}
		(boolean)$res ? exit('0') : exit('1');
	}
}